
package com.compuvest.webstat;

// <editor-fold defaultstate="collapsed" desc="import">
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// </editor-fold>

@WebServlet("/webstat/getFromMySQL")
public class GetFromMySQL extends HttpServlet {

    private WMySQL mysql;
    private WMail mail;
    //private com.compuvest.webstat.MyUtils utils;

// <editor-fold defaultstate="collapsed" desc="init()">

    @Override
    public void init(ServletConfig config) throws ServletException {
	super.init(config);

        mysql = (WMySQL)config.getServletContext().getAttribute("websql");
	if(mysql == null) {
            System.out.println("GetFromMySQL Error websql=null");
        }
        mail = (WMail)config.getServletContext().getAttribute("webmail");
	if(mail == null) {
            System.out.println("GetFromMySQL Error wmail=null");
        }

        //utils = new com.compuvest.webstat.MyUtils();

        System.out.println("GetFromMySQL init");
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="processRequest()">

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        String json = "";
        String table = request.getParameter("table");
        if(table != null) {
            // current page
            int currentPage = getInt(request.getParameter("curPage"));
            // how many show customers on page (15,25,50)
            int onPage = getInt(request.getParameter("onPage"), 30);
            int custid = getInt(request.getParameter("custid"));
            String begDate = request.getParameter("beg"); // start Date
            String endDate = request.getParameter("end"); // finish Date
            String exec = getString(request.getParameter("ex"));

            String groupid = getString(request.getParameter("groupid"));
            String name = getString(request.getParameter("name"));

            if("test".equals(table)) {
                json = "{}";
            }
            else if("sugcust".equals(table)) {
                json = mysql.getSuggesion(request.getParameter("q"), request.getParameter("c")); // q=query, c= colonName
            }
            else if("sugord".equals(table)) {
                json = mysql.getOrderSuggesion(request.getParameter("q"), request.getParameter("c")); // q=query, c= colonName
            }
            else if("custs".equals(table)) {
                json = mysql.getCustomers(begDate, endDate, currentPage, onPage, custid);
            }
            else if("custorders".equals(table)) {
                json = mysql.getCustomersOrders(request.getParameter("cid"), currentPage, onPage);
            }
            else if("orders".equals(table)) {
                int orderid = getInt(request.getParameter("orderid"));
                json = mysql.getOrders(begDate, endDate, currentPage, onPage, orderid);
            }
            else if("order".equals(table)) {
                json = mysql.getOrder(request.getParameter("oid"));
            }
            else if("advorders".equals(table)) {
                json = mysql.getOrdersForAdvert(request.getParameter("adv"), begDate, endDate, currentPage, onPage);
            }
            else if("resellers".equals(table)) {
                json = mysql.getResellers(begDate, endDate, currentPage, onPage, custid);
            }
            else if("resinfo".equals(table)) {

                json = mysql.getResellerInfo(custid);
            }
            else if("ressave".equals(table)) {

                String accwareAccount = request.getParameter("accw");
                String type = request.getParameter("ckbox");
                String notes = request.getParameter("note");
                String email = request.getParameter("email");
                json = mysql.saveResellerInfo(custid, accwareAccount, type, notes);

                if("R".equals(type)) {

                    //utils.saveResellerToAccware(email);

                    // send email
                    mail.sendAproveReseller(accwareAccount, notes, email);
                }
            }
            // <editor-fold defaultstate="collapsed" desc="GOOGLE">
            else if("google".equals(table)) {
                double cpcmax = getDouble(request.getParameter("cpcmax"));
                double cpcnt = getDouble(request.getParameter("cpcnt"));

                if("groups".equals(exec)) {
                    json = mysql.getGoogleTable();
                }
                else if("getgroup".equals(exec)) {
                    json = mysql.getGoogleGroup(groupid);
                }
                else if("updategroup".equals(exec)) {
                    json = mysql.updateGroup(
                        groupid,
                        name,
                        request.getParameter("fname"),
                        cpcmax,
                        cpcnt,
                        request.getParameter("actv")
                    );
                }
                else if("creategroup".equals(exec)) {
                    json = mysql.createGroup(
                        name,
                        request.getParameter("fname"),
                        cpcmax,
                        cpcnt,
                        request.getParameter("actv")
                    );
                }
                else if("erasegroup".equals(exec)) {
                    json = mysql.eraseGroup(groupid);
                }
                else if("getcat".equals(exec)) {
                    json = mysql.getCategory(groupid);
                }
                else if("getscat".equals(exec)) {
                    json = mysql.getSubCategory(request.getParameter("cid"));
                }
                else if("save".equals(exec)) {
                    json = mysql.saveCategories(groupid, request.getParameter("catid"), request.getParameter("cb"));
                }
            }
            // </editor-fold>
            // <editor-fold defaultstate="collapsed" desc="EPY">
            else if("epy".equals(table)) {
                String id = request.getParameter("id");
                String cid = request.getParameter("cid");
                String vid = request.getParameter("vid");
                String gid = request.getParameter("gid");
                String cb = request.getParameter("cb");

                if("getVends".equals(exec)) {
                    json = mysql.getEpyVendors();
                }
                else if("getVendsNew".equals(exec)) {
                    json = mysql.getEpyVendorsNew(currentPage, onPage);
                }
                else if("getVend".equals(exec)) {
                    json = mysql.getEpyVendor(vid);
                }
                else if("updVend".equals(exec)) {
                    json = mysql.updateEpyVendor(vid, cb);
                }
                else if("getVendCats".equals(exec)) {
                    json = mysql.getEpyVendorCategories(vid);
                }
                else if("saveVendCats".equals(exec)) {
                    json = mysql.saveEpyVendorCategories(cb);
                }
                // groups
                else if("groups".equals(exec)) {
                    json = mysql.getEpyGroups();
                }
                else if("getEpyGroup".equals(exec)) {
                    json = mysql.getEpyGroup(gid, request.getParameter("adv"));
                }
                else if("upEpyGroup".equals(exec)) {
                    json = mysql.updateEpyGroup(gid, cb);
                }
                else if("crEpyGroup".equals(exec)) {
                    json = mysql.createEpyGroup(cb);
                }
                else if("erEpyGroup".equals(exec)) {
                    json = mysql.eraseEpyGroup(gid);
                }
                else if("drag".equals(exec)) {
                    json = mysql.saveEpyDrag(getInt(request.getParameter("nzone")), getInt(request.getParameter("ozone")), cid);
                }
                else if("getGroupSubcat".equals(exec)) {
                    json = mysql.getEpySubCategory(gid);
                }
                else if("getItems".equals(exec)) {
                    json = mysql.getEpyItems(currentPage, cid);
                }
                else if("getEpyEditUser".equals(exec)) {
                    json = mysql.getEpyEditUser(id);
                }
                else if("upEpyUser".equals(exec)) {
                    json = mysql.updateEpyUser(id, cb);
                }
                else if("crEpyUser".equals(exec)) {
                    json = mysql.createEpyUser(cb);
                }
                else if("erEpyUser".equals(exec)) {
                    json = mysql.deleteEpyUser(id);
                }
                //else if("getUserItems".equals(exec)) {
                //    json = mysql.getEpyUserItems(request.getParameter("uid"));
                //}
                else if("attItem".equals(exec)) {
                    json = mysql.attachItemToUser(request.getParameter("iid"),request.getParameter("uid"));
                }
                //else if("getEpyEditItem".equals(exec)) {
                //    json = mysql.getEpyEditItem(request.getParameter("iid"));
                //}
                //else if("delEpyUserItem".equals(exec)) {
                //    json = mysql.deleteEpyUserItem(request.getParameter("iid"));
                //}
                //else if("upEpyUserItem".equals(exec)) {
                //    json = mysql.updateEpyUserItem(request.getParameter("iid"), cb);
                //}
            }
            // </editor-fold>
            // <editor-fold defaultstate="collapsed" desc="Coupon">
            else if("cupon".equals(table)) {
                if("getItem".equals(exec)) {
                    json = mysql.getCouponItem(request.getParameter("sku"));
                }
                else if("saveCoupon".equals(exec)) {
                    json = mysql.saveCoupon(request.getParameter("iid"), request.getParameter("code"), request.getParameter("proc"), request.getParameter("price"), request.getParameter("date"));
                }
                else if("updateCoupon".equals(exec)) {
                    json = mysql.updateCoupon(request.getParameter("id"), request.getParameter("date"));
                }

            }
            // </editor-fold>
            // <editor-fold defaultstate="collapsed" desc="ItemTracking">
            else if("ittrack".equals(table)) {
                if("getAdv".equals(exec)) {
                    json = mysql.getAdvert();
                }
                else if("getcat".equals(exec)) {
                    json = mysql.getItemTrackingCategory();
                }
                else if("getscat".equals(exec)) {
                    json = mysql.getItemTrackingSubcategory(request.getParameter("aid"), request.getParameter("cid"));
                }
                else if("save".equals(exec)) {
                    json = mysql.saveItemTrackingSubcategories(request.getParameter("aid"), request.getParameter("cid"), request.getParameter("cb"));
                }
            }
            // </editor-fold>
            // <editor-fold defaultstate="collapsed" desc="GoogleFeed">
            else if("gfeed".equals(table)) {
                if("getItem".equals(exec)) {
                    json = mysql.getGooleFeedMfrNumber(request.getParameter("mfr"));
                }
                else if("getItems".equals(exec)) {
                    json = mysql.getItemsForGoogle(
                        currentPage,
                        getInt(request.getParameter("vid")),
                        getInt(request.getParameter("cid")),
                        getInt(request.getParameter("uid")),
                        getInt(request.getParameter("aid")),
                        getInt(request.getParameter("srt")),
                        getString(request.getParameter("drt"), "ASC"));
                }
                else if("getItemsSKU".equals(exec)) {
                    json = mysql.getItemsSKUForGoogle(request.getParameter("sku"));
                }
                else if("getVendors".equals(exec)) {
                    json = mysql.getVendorsForGoole();
                }
                else if("getHistory".equals(exec)) {
                    json = mysql.getUserHistory(request.getParameter("iid"));
                }
                else if("getDisc".equals(exec)) {
                    json = mysql.getDiscount(getInt(request.getParameter("cid")));
                }
                else if("saveDisc".equals(exec)) {
                    mysql.saveDiscount(
                        getInt(request.getParameter("cid")),
                        getInt(request.getParameter("sid")),
                        getDouble(request.getParameter("dct")),
                        getDouble(request.getParameter("a0")),
                        getDouble(request.getParameter("a1")),
                        getDouble(request.getParameter("a2")),
                        getDouble(request.getParameter("a3")),
                        getDouble(request.getParameter("a4")),
                        getDouble(request.getParameter("a5"))
                    );
                }
            }
            // </editor-fold>
            // <editor-fold defaultstate="collapsed" desc="DropPrice & PromoCode">
            else if("dppc".equals(table)) {
                if("getPromoPrice".equals(exec)) {
                    json = mysql.getPromoPriceItem(request.getParameter("iid"), request.getParameter("email"));
                }
                else if("savePromoPrice".equals(exec)) {
                    String email = request.getParameter("email");
                    String promCode = request.getParameter("promCode");
                    String expDate = request.getParameter("expDate");
                    String itemid = request.getParameter("itemid");
                    String itmName = request.getParameter("itmName");
                    String sellPrice = request.getParameter("sellPrice");
                    String promPrice = request.getParameter("promPrice");
                    String percent = request.getParameter("percent");
                    String page = request.getParameter("page");

                    mail.sendPromoPrice(email, promCode, itemid, itmName, sellPrice, promPrice, percent, expDate, page);
                    json = mysql.saveCoupon(itemid, promCode, percent, "0.00", expDate);
                }
            }
            // </editor-fold>
            // <editor-fold defaultstate="collapsed" desc="Login">
            else if("login".equals(table)) {
                String userid = request.getParameter("id");
                if("getUser".equals(exec)) {
                    json = mysql.getUserTabsMask(request.getParameter("user"), request.getParameter("passwd"));
                }
                else if("getUsers".equals(exec)) {
                    json = mysql.getUsers();
                }
                else if("updateRootUser".equals(exec)) {
                    json = mysql.updateRootUser(userid, request.getParameter("passwd"), request.getParameter("mask"), request.getParameter("act"));
                }
            }
            // </editor-fold>
            if("stat".equals(table)) {
                json = mysql.getStatus();
            }
            if("amazon".equals(table)) {
                json = mysql.getAmazonStatus();
            }

            PrintWriter out = response.getWriter();
            try {
		out.print(json);
            }
            finally {
		out.close();
            }

        }
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getString()">

    protected String getString(String value) {
        return value == null ? "" : value;
    }

    protected String getString(String value, String defValue) {
        return value == null ? defValue : value;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getInt()">

    protected int getInt(String value) {

        return getInt(value, 0);
    }

    protected int getInt(String value, int defValue) {

        int integer = defValue;
        try {
            integer = (value == null) ? defValue : Integer.parseInt(value);
        }
        catch(Exception ignore) { }

        return integer;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getDouble()">

    protected double getDouble(String value) {

        double dbl = 0d;
        try {
            dbl = (value == null) ? 0d : Double.parseDouble(value);
        }
        catch(Exception ignore) { }

        return dbl;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    public String getServletInfo() {
        return "GetFromMySQL()";
    }

    @Override
    public void destroy() {
        mysql = null;
        mail = null;

        System.out.println("GetFromMySQL() Destroy:");
    }
// </editor-fold>

}
